﻿using System;
using System.Globalization;
using System.Web.UI;
using System.Web.Security.AntiXss;
using System.Web.UI.WebControls;
using InhollandAir.auxiliary;

namespace InhollandAir
{
    public partial class PlanBook : Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            CustomerFactory.TryLogin((customer, success) =>
            {
                if (!success) Response.Redirect("Login.aspx");
                Customer = customer;
            });

            ChooseFlight.DidChangeAirportFrom += ChooseFlight_DidChangeAirport;
            ChooseFlight.DidChangeAirportTo += ChooseFlight_DidChangeAirport;

            if (Page.IsPostBack) return;

            // Set all cars
            foreach (var car in Sql.GetAllCarMakes())
                ddlCars.Items.Add(car);

            // Set all hotel countries
            foreach (var hotel in Sql.GetHotels())
                ddlHotels.Items.Add(hotel);
        }

        protected void Logout(object sender, EventArgs e)
        {
            CustomerFactory.Logout(true);
        }

        void ChooseFlight_DidChangeAirport(object o)
        {
            if(ChooseFlight.AirportFrom != null) 
                Summary.AirportFrom1 = ChooseFlight.AirportFrom.Name;
            if(ChooseFlight.CountryFrom != null)
                Summary.CountryFrom1 = ChooseFlight.CountryFrom.Name;
            
            if (ChooseFlight.AirportTo != null)
                Summary.AirportTo1 = ChooseFlight.AirportTo.Name;
            
            if(ChooseFlight.CountryTo != null)
                Summary.CountryTo1 = ChooseFlight.CountryTo.Name;
            
            FlightChosen(ChooseFlight.CountryFrom != null && ChooseFlight.AirportFrom != null && ChooseFlight.CountryTo != null &&
                ChooseFlight.AirportTo != null);
        }

        private void FlightChosen(bool success)
        {
            if (!success)
            {
                flightPanel.Visible = false;
                return;
            }

            var label = string.Format("{0} - {1} \n {2} - {3}", Summary.CountryFrom1, Summary.AirportFrom1,
                Summary.CountryTo1, Summary.AirportTo1);
            lblFlight1.Text = AntiXssEncoder.HtmlEncode(label, false);

            var routes = Sql.GetRoutesWithAirports(ChooseFlight.AirportFrom, ChooseFlight.AirportTo);
            if (routes.Count > 0)
            {
                var date = Convert.ToDateTime(Summary.DateLeave);
                var flights = Sql.GetFlightsForRouteWithStartDate(routes[0], date);

                ddlFlights.Items.Clear();
                ddlFlights.Items.Add(AntiXssEncoder.HtmlEncode("Choose date ...", false));

                foreach (var flight in flights)
                {
                    var show = string.Format("{0}", flight.StartDate.ToString("dd-MM-yyyy HH:mm"));
                    ddlFlights.Items.Add(new ListItem(AntiXssEncoder.HtmlEncode(show, false), AntiXssEncoder.HtmlEncode(flight.Id.ToString(CultureInfo.InvariantCulture), false)));
                
                }
                ddlFlights.Enabled = true;
             }
            else
            {
                ddlFlights.Items.Clear();
                ddlFlights.Items.Add(AntiXssEncoder.HtmlEncode("No flights found ...", false));
                lblFlightDate.Text = AntiXssEncoder.HtmlEncode("-", false);
                ddlFlights.Enabled = false;
            }

            flightPanel.Visible = true;
        }

        #region Field Populators

        #endregion WebMethods

        protected void DdlPersonCountSelectedIndexChanged(object sender, EventArgs e)
        {
            int size;
            if (!int.TryParse(ddlPersonCount.SelectedValue, out size)) return;

            Summary.TravelPartySize = size;
            lblTravelPartySize.Text = AntiXssEncoder.HtmlEncode(Summary.TravelPartySize + " people", false);
        }

        protected void BtnSaveDatesClick(object sender, EventArgs e)
        {
            DateTime date;
            if (!DateTime.TryParse(dateLeave.Text.Trim(), out date) || !string.IsNullOrEmpty(dateLeave.Text.Trim())) return;
            Summary.DateLeave = date;

            lblLeaveDate.Text = AntiXssEncoder.HtmlEncode(Summary.DateLeave.ToString("dd/MM/yyyy"),false);
        }

        protected void DdlCarsSelectedIndexChanged(object sender, EventArgs e)
        {
            int id;
            if(!int.TryParse(ddlCars.SelectedValue, out id)) return;
            if (id < 0) return;

            var carSpecs = Sql.GetCarSpecifications(id.ToString(CultureInfo.InvariantCulture));
            lblCarType.Text = AntiXssEncoder.HtmlEncode(carSpecs["Specifications"].Split(':')[0], false);
            lblCarCapacity.Text = AntiXssEncoder.HtmlEncode(carSpecs["Specifications"].Split(':')[1], false);
            Summary.RentalCar = id.ToString(CultureInfo.InvariantCulture);
            lblRentalCar.Text = AntiXssEncoder.HtmlEncode(string.Format("{0}, {1}, {2} people", Summary.RentalCar, 
                carSpecs["Specifications"].Split(':')[0], carSpecs["Specifications"].Split(':')[1]), false);
        }

        protected void DdlHotelsSelectedIndexChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ddlHotels.SelectedValue)) return;
            Summary.Hotel = ddlHotels.SelectedValue;
            lblHotel.Text = AntiXssEncoder.HtmlEncode(ddlHotels.SelectedItem.Text, false);
        }

        protected void ddlFlights_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            int id;
            if(!int.TryParse(ddlFlights.SelectedValue, out id)) return;

            if (id < 1)
            {
                lblFlightDate.Text = AntiXssEncoder.HtmlEncode("-", false);
                return;
            }

            var flight = Sql.GetFlightWithId(id);
            Flight = flight;
            lblFlightDate.Text = AntiXssEncoder.HtmlEncode(flight.StartDate.ToString("dd-MM-yyyy HH:mm"), false);
        }

        protected void Book(object sender, EventArgs e)
        {
            if (!Page.IsValid)
            {
                Response.Write("<script>alert('Please correct the invalid values and try again.');</script>");
                return;
            }
            if (Flight != null && Summary.TravelPartySize > 0 && !string.IsNullOrEmpty(Summary.CountryFrom1) && !string.IsNullOrEmpty(Summary.AirportFrom1) 
                && !string.IsNullOrEmpty(Summary.CountryTo1) && !string.IsNullOrEmpty(Summary.AirportTo1))
            {
                Session["booking_id"] = Sql.InsertBooking(Customer.Id, Flight.Id, Summary.TravelPartySize, 1);
                Session["flight_id"] = Flight.Id;
                Session["amount_persons"] = Summary.TravelPartySize;
                Response.Redirect("Checkout.aspx");
            }
            else
                Response.Write("<script>alert('Please correct the invalid values and try again.');</script>");
        }

        private static Flight Flight { get; set; }
        private static Customer Customer { get; set; }
    }
}